<?php
/**
 * 审批控制器
 */

declare (strict_types = 1);

namespace app\controller\home;

use app\BaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use think\facade\Request;

class Approve extends BaseController
{

    /**
     * 获取审批模块和分类列表
     */
    public function index()
    {
        try {
            $userId = $this->getUserId();
            $departmentId = $this->getUserDepartmentId();
            
            // 获取启用的审批模块
            $modules = Db::name('flow_module')
                ->where(['status' => 1])
                ->order('sort', 'desc')
                ->select()
                ->toArray();
            
            $whereOr = [];
            if ($userId > 1) {
                $whereOr[] = ['department_ids', '=', ''];
                $whereOr[] = ['department_ids', 'like', '%,' . $departmentId . ',%'];
                $whereOr[] = ['department_ids', 'like', $departmentId . ',%'];
                $whereOr[] = ['department_ids', 'like', '%,' . $departmentId];
                $whereOr[] = ['department_ids', '=', $departmentId];
            }
            
            foreach ($modules as &$module) {
                // 获取模块下的审批分类
                $query = Db::name('flow_cate')
                    ->where([
                        ['module_id', '=', $module['id']],
                        ['status', '=', 1],
                        ['is_list', '=', 1]
                    ]);
                
                if (!empty($whereOr)) {
                    $query->where(function ($query) use ($whereOr, $departmentId) {
                        foreach ($whereOr as $condition) {
                            if (is_array($condition)) {
                                $query->where($condition[0], $condition[1], $condition[2]);
                            }
                        }
                        // 使用OR连接条件
                        $query->where(function ($subQuery) use ($departmentId) {
                            $subQuery->where('department_ids', '=', '');
                            $subQuery->whereOr('department_ids', 'like', '%,' . $departmentId . ',%');
                            $subQuery->whereOr('department_ids', 'like', $departmentId . ',%');
                            $subQuery->whereOr('department_ids', 'like', '%,' . $departmentId);
                            $subQuery->whereOr('department_ids', '=', $departmentId);
                        });
                    });
                }
                
                $module['list'] = $query->select()->toArray();
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $modules
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取我申请的审批列表
     */
    public function mylist()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            $status = isset($param['status']) ? (int)$param['status'] : 0;
            
            // 构建查询条件
            $where = "delete_time = 0 AND admin_id = " . $userId;
            
            // 根据状态筛选
            if ($status == 1) {
                // 待审核和审核中
                $where .= " AND check_status < 2";
            } else if ($status == 2) {
                // 审核通过
                $where .= " AND check_status = 2";
            } else if ($status == 3) {
                // 审核不通过或撤销
                $where .= " AND check_status > 2";
            }
            
            $list = $this->getApproveList($where, $page, $limit);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list['data'],
                'count' => $list['total']
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取待我审批的列表
     */
    public function checklist()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            $status = isset($param['status']) ? (int)$param['status'] : 0;
            
            // 构建查询条件
            $where = "delete_time = 0";
            
            if ($status == 0) {
                // 全部待审批（当前审批人或历史审批人）
                $where .= " AND (FIND_IN_SET('{$userId}', check_uids) OR FIND_IN_SET('{$userId}', check_history_uids))";
            } else if ($status == 1) {
                // 当前审批人
                $where .= " AND FIND_IN_SET('{$userId}', check_uids)";
            } else if ($status == 2) {
                // 历史审批人
                $where .= " AND FIND_IN_SET('{$userId}', check_history_uids)";
            }
            
            $list = $this->getApproveList($where, $page, $limit);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list['data'],
                'count' => $list['total']
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取抄送我的审批列表
     */
    public function copylist()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            $status = isset($param['status']) ? (int)$param['status'] : 0;
            
            // 构建查询条件
            $where = "delete_time = 0";
            
            // 根据状态筛选
            if ($status == 1) {
                // 待审核和审核中
                $where .= " AND check_status < 2";
            } else if ($status == 2) {
                // 审核通过
                $where .= " AND check_status = 2";
            } else if ($status == 3) {
                // 审核不通过或撤销
                $where .= " AND check_status > 2";
            }
            
            // 关联抄送人
            $where .= " AND FIND_IN_SET('{$userId}', check_copy_uids)";
            
            $list = $this->getApproveList($where, $page, $limit);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list['data'],
                'count' => $list['total']
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取全部审批列表（需要权限）
     */
    public function all()
    {
        try {
            $param = Request::param();
            $userId = $this->getUserId();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            $status = isset($param['status']) ? (int)$param['status'] : 0;
            
            // 检查是否有权限访问全部审批
            $auth = Db::name('admin')
                ->where('id', $userId)
                ->where('role_id', 'in', [1, 2]) // 假设只有超级管理员和管理员有权限
                ->find();
            
            if (!$auth) {
                return json(['code' => 403, 'msg' => '无权限访问']);
            }
            
            // 构建查询条件
            $where = "delete_time = 0";
            
            // 根据状态筛选
            if ($status == 1) {
                // 待审核和审核中
                $where .= " AND check_status < 2";
            } else if ($status == 2) {
                // 审核通过
                $where .= " AND check_status = 2";
            } else if ($status == 3) {
                // 审核不通过或撤销
                $where .= " AND check_status > 2";
            }
            
            // 按申请人筛选
            if (!empty($param['uid'])) {
                $where .= " AND admin_id = " . (int)$param['uid'];
            }
            
            $list = $this->getApproveList($where, $page, $limit);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list['data'],
                'count' => $list['total']
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取审批列表的通用方法
     */
    private function getApproveList($where, $page, $limit)
    {
        // 获取所有启用的审批分类
        $categories = Db::name('flow_cate')
            ->field('name, check_table, title')
            ->where('status', 1)
            ->select()
            ->toArray();
        
        $prefix = config('database.connections.mysql.prefix');
        $sqlParts = [];
        $sqlCounts = [];
        $processedTables = [];
        
        foreach ($categories as $category) {
            $tableName = $category['check_table'];
            
            // 避免重复处理相同表
            if (in_array($tableName, $processedTables)) {
                continue;
            }
            
            $checkName = $category['title'];

            // 验证表名格式，防止SQL注入
            if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $tableName)) {
                continue;
            }

            $fullTableName = $prefix . $tableName;

            // 检查表是否存在
            $isTableExists = Db::query("SHOW TABLES LIKE ?", [$fullTableName]);
            if (empty($isTableExists)) {
                continue;
            }
            
            // 构建不同表的SQL查询（转义变量防止SQL注入）
            $safeCheckName = addslashes($checkName);

            if ($tableName == 'invoice' || $tableName == 'ticket') {
                $sqlPart = "SELECT id, admin_id, did, create_time, check_status, check_flow_id, check_step_sort, check_uids, check_last_uid, check_history_uids, check_copy_uids, check_time, '{$tableName}' as table_name, '{$safeCheckName}' as check_name, invoice_type, '{$safeCheckName}' as types FROM {$fullTableName} WHERE {$where}";
            } else if ($tableName == 'approve') {
                $sqlPart = "SELECT id, admin_id, did, create_time, check_status, check_flow_id, check_step_sort, check_uids, check_last_uid, check_history_uids, check_copy_uids, check_time, '{$tableName}' as table_name, '{$safeCheckName}' as check_name, '{$safeCheckName}' as invoice_type, types FROM {$fullTableName} WHERE {$where}";
            } else {
                $sqlPart = "SELECT id, admin_id, did, create_time, check_status, check_flow_id, check_step_sort, check_uids, check_last_uid, check_history_uids, check_copy_uids, check_time, '{$tableName}' as table_name, '{$safeCheckName}' as check_name, '{$safeCheckName}' as invoice_type, '{$safeCheckName}' as types FROM {$fullTableName} WHERE {$where}";
            }

            $sqlCount = "SELECT COUNT(*) AS count FROM {$fullTableName} WHERE {$where}";

            $sqlParts[] = $sqlPart;
            $sqlCounts[] = $sqlCount;
            $processedTables[] = $tableName;
        }
        
        if (empty($sqlParts)) {
            return ['data' => [], 'total' => 0];
        }
        
        // 使用UNION ALL连接各个部分
        $unionSql = implode(" UNION ALL ", $sqlParts);
        
        // 计算总数
        $totalCount = 0;
        foreach ($sqlCounts as $sql) {
            $countResult = Db::query($sql);
            $totalCount += $countResult[0]['count'];
        }
        
        // 添加排序和分页逻辑
        $offset = ($page - 1) * $limit;
        $finalSql = $unionSql . " ORDER BY create_time DESC LIMIT {$offset}, {$limit}";
        
        // 执行查询
        $result = Db::query($finalSql);
        
        // 处理结果
        foreach ($result as &$row) {
            $row['create_time'] = date('Y-m-d H:i', $row['create_time']);
            $row['admin_name'] = Db::name('admin')->where('id', $row['admin_id'])->value('name');
            $row['department'] = Db::name('department')->where('id', $row['did'])->value('title');
            
            // 审核状态名称
            $checkStatusNames = [
                0 => '待审核',
                1 => '审核中',
                2 => '审核通过',
                3 => '审核不通过',
                4 => '撤销审核'
            ];
            $row['check_status_str'] = isset($checkStatusNames[$row['check_status']]) ? $checkStatusNames[$row['check_status']] : '未知';
            
            // 当前审批人
            if ($row['check_status'] == 1 && !empty($row['check_uids'])) {
                $checkUsers = Db::name('admin')->where('id', 'in', $row['check_uids'])->column('name');
                $row['check_users'] = implode(',', $checkUsers);
            } else {
                $row['check_users'] = '-';
            }
            
            // 抄送人
            if (!empty($row['check_copy_uids'])) {
                $checkCopyUsers = Db::name('admin')->where('id', 'in', $row['check_copy_uids'])->column('name');
                $row['check_copy_users'] = implode(',', $checkCopyUsers);
            } else {
                $row['check_copy_users'] = '-';
            }
            
            // 审批类型名称
            $checkName = $row['check_name'];
            if ($row['table_name'] == 'invoice' || $row['table_name'] == 'ticket') {
                if ($row['invoice_type'] == 0) {
                    $checkName = $row['table_name'] . 'a';
                } else {
                    $checkName = $row['table_name'];
                }
            }
            if ($row['table_name'] == 'approve') {
                $checkName = 'approve_' . $row['types'];
            }
            
            $flowCate = Db::name('flow_cate')->where('name', $checkName)->find();
            if ($flowCate) {
                $row['types_name'] = $flowCate['title'];
                $row['view_url'] = $flowCate['view_url'];
                $row['add_url'] = $flowCate['add_url'];
            }
        }
        
        return ['data' => $result, 'total' => $totalCount];
    }
}